import AsyncStorage from '@react-native-async-storage/async-storage'

// 存储key-value型数据
const set = async(storageKey, value) => {
  try {
    await AsyncStorage.setItem(storageKey, value)
  } catch (error) {
    // saving error
  }
}

// 获取key-value型数据
const get = (storageKey, callback) => {
  try {
    AsyncStorage.getItem(storageKey, callback)
  } catch(e) {
    // error reading value
  }
}

// 移除指定的Key
const remove = async (storageKey) => {
  try {
    await AsyncStorage.removeItem(storageKey)
  } catch(e) {
    // remove error
  }
}

// 存储json格式数据
const setJson = async (storageKey, value) => {
  try {
    const jsonValue = JSON.stringify(value)
    await AsyncStorage.setItem(storageKey, jsonValue)
  } catch (e) {
    // saving error
  }
}

// 获取json格式数据
const getJson = async (storageKey) => {
  try {
    const jsonValue = await AsyncStorage.getItem(storageKey)
    return jsonValue != null ? JSON.parse(jsonValue) : null;
  } catch(e) {
    // error reading value
  }

  return null
}


export default {
  set,
  get,
  remove,
  setJson,
  getJson
}